package com.zhiwang.planet.ui.entertain

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.iBookStar.views.YmConfig
import com.zhiwang.planet.BR
import com.zhiwang.planet.BuildConfig
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.util.Throttle
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.event.PlayAdVideoEvent
import com.zhiwang.planet.mvp.v.AuthView
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.entity.main.Banner
import com.zhiwang.planet.mvvm.model.entity.main.H5HotGame
import com.zhiwang.planet.mvvm.model.entity.main.H5Record
import com.zhiwang.planet.ui.WebViewActivity
import com.zhiwang.planet.ui.my.TradingMarketActivity
import com.zhiwang.planet.util.*
import io.reactivex.Observable
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.entertain_bean_exchange_menu_dialog.*
import kotlinx.android.synthetic.main.entertain_bean_exchange_menu_dialog.view.*
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject


@ActivityScope
class EntertainV3ViewModel @Inject constructor(var restApi: RestApi, var context: AppCompatActivity) : ViewModel() {


    lateinit var authView: AuthView

    val beanCount = MutableLiveData<String>()

    val records = MutableLiveData<List<H5Record>>()

    val h5Reward = MutableLiveData<String>()

    val recordItemBinding = OnItemBind<H5Record> { itemBinding, position, item ->
        if (item.type == 1) {
            //empty
            itemBinding.set(BR.vm, R.layout.item_played_web_game_empty)
        } else if (item.type == 2) {
            itemBinding.set(BR.vm, R.layout.item_played_web_game_more)
        } else {
            itemBinding.set(BR.vm, R.layout.item_played_web_game)
        }

        itemBinding.bindExtra(BR.clickListener, this)
    }

    var oldGameId = ""

    val hotGameDatas = MutableLiveData<List<H5HotGame>>()

    val hotGameBinding = OnItemBind<H5HotGame> { itemBinding, position, item ->


        if (item.type == 0) {
            itemBinding.set(BR.vm, R.layout.item_web_game)
        } else if (item.type == 1) {
            itemBinding.set(BR.vm, R.layout.item_web_game_more)
        }

        itemBinding.bindExtra(BR.extra, this)


    }

    //小游戏

    @Throttle
    fun miniGame() {

        context.quickStartActivity(MiniGameActivity::class.java)
    }


    //视频
    @Throttle
    fun playVideo() {
        EventBus.getDefault().post(PlayAdVideoEvent)
    }

    //小说
    @Throttle
    fun novel() {
        YmConfig.openReader()
    }

    //网游
    @Throttle
    fun h5Game() {
        WebViewActivity.load(context, SkStore.dwIndex)
    }


    @Throttle
    fun h5Game(id: String) {
        if (BuildConfig.DEBUG)
            Toaster.message("hi click game item")
        oldGameId = id
        WebViewActivity.load(context, SkStore.dwGameUrl(id, TokenManager.webviewHeaderUserid()))
    }

    @Throttle
    fun playRecord() {
        WebViewActivity.load(context, SkStore.dwLatestUrl(TokenManager.webviewHeaderUserid()))
    }

    fun loadPrevGame() {
        if (TextUtils.isEmpty(oldGameId).not())
            h5Game(oldGameId)
    }


    @Throttle

    fun lucky3() = WebViewActivity.load(context, Store.LUCKY3)


    @Throttle

    fun _28() {
        WebViewActivity.load(context, Store.SFSX)
    }


    @Throttle

    fun _90s() {
        WebViewActivity.load(context, Store.URL_FAST28)
    }


    @Throttle
    fun navBeanMarket() {
//        context.quickStartActivity(TradingMarketActivity::class.java)

        val view = LayoutInflater.from(context).inflate(R.layout.entertain_bean_exchange_menu_dialog, null)
        val create = AlertDialog.Builder(context)
                .setView(view)
                .create()

        view.item_1.setOnClickListener {

            WebViewActivity.load(context, Store.URL_MEMBER_SHIP)
            create.dismiss()
        }
        view.item_2.setOnClickListener {
            context.quickStartActivity(TradingMarketActivity::class.java)
            create.dismiss()

        }

        view.item_3.setOnClickListener {
            h5Game()
            create.dismiss()
        }

        create.show()
    }

    fun loadBean() {
        restApi.getUserInfoEx()
                .arrange(Consumer {

//                    beanCount.value = String.format("%,d", it.bean.toLong())

                }
                        , Consumer {

                },
                        Action {

                        })
    }

    fun load() {
        if (TokenManager.isLoginValid().not())
            return
        loadBanner()
        loadRecord()
        loadBean()
        loadHot()
    }

    /**
     * 加载玩过的游戏
     */
    fun loadRecord() {

        restApi.getH5PlayedRecord(TokenManager.webviewHeaderUserid())
                .arrange(Consumer {

                    var datas: ArrayList<H5Record> = it as ArrayList<H5Record>

                    if (datas.isEmpty()) {
                        val elements = H5Record("", "", "", "", "")
                        elements.type = 1
                        datas = arrayListOf(elements)
                    } else {
                        if (datas.size > 7) {
                            datas = arrayListOf<H5Record>(*(datas.subList(0, 7) as List<H5Record>).toTypedArray())
                            val elements = H5Record("", "", "", "", "")
                            elements.type = 2
                            datas.add(elements)
                        }

                    }

                    records.value = datas

                }, Consumer {

                    authView.onError(it)
                }, Action {

                })

        loadHot()
        loadBean()
    }

    /**
     * 加载热门推荐
     * id: "1938257615",
    uid: 1988067250,
    pTime: 1596523429437,
    channel: 13697,
    name: "极限逃亡",
    gameIcon: "http://img.m3guo.com/group3/M00/00/FC/wKgMHF8f7nWAPwXdAAFND6qg8Ho029.png"
    },
     */

    val TAG = "EntertainV3ViewModel"

    @SuppressLint("CheckResult")
    fun loadHot() {

        //fixme mock data

        restApi.getHotH5Game()
                .arrange(Consumer {

                    hotGameDatas.value =
                            if (it.size > 6) {
                                val subList = (it as ArrayList<H5HotGame>).subList(0, 6)
                                subList.add(H5HotGame("", "", "", "").apply { type = 1 })
                                subList
                            } else it
                },
                        Consumer {
                            authView.onError(it)
                        }
                        , Action {

                })

    }


    val banner = MutableLiveData<List<Banner>>()
    fun loadBanner() {
        if (banner.value?.isNotEmpty() == true)
            return
        restApi.getYuleBanner()
                .arrange(Consumer {

                    banner.value = it
                }, Consumer {

                }, Action {

                })
    }
}